package com.cloud.shopping.mq;

import com.cloud.shopping.constants.RocketConstants;
import com.cloud.shopping.order.mapper.OrderRefundMapper;
import com.cloud.shopping.order.model.OrderRefund;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author John.zhang
 * @version Id: RefundTransactionListener, v 1.0 2021/1/6 16:29 ZhiYong Exp $
 */

@Component
@RocketMQTransactionListener(txProducerGroup = RocketConstants.PRODUCER_GROUP)
public class RefundTransactionListener implements RocketMQLocalTransactionListener {

    @Resource
    private OrderRefundMapper orderRefundMapper;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            //退款申请记录
            OrderRefund orderRefund = (OrderRefund) arg;
            orderRefundMapper.deleteById(orderRefund.getId());
            int count = orderRefundMapper.insert(orderRefund);
            if(count<=0){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        return RocketMQLocalTransactionState.COMMIT;
    }
}
